﻿using AutoMapper;
using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Keep.API.Appliction.Command.DepartmentFile
{
    /// <summary>
    /// 部门创建命令处理器
    /// </summary>
    public class DepartmentCreateHandler : IRequestHandler<DepartmentCreateCommon, Result>
    {
        private readonly IBaseRepositorys<Department> _DepartmentRep;
        IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRep"></param>
        /// <param name="mapper"></param>
        public DepartmentCreateHandler(IBaseRepositorys<Department> departmentRep, IMapper mapper)
        {
            _DepartmentRep = departmentRep;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DepartmentCreateCommon request, CancellationToken cancellationToken)
        {

            var Result = new Result() { Code = (int)CodeEnum.success, Messege = "创建成功" };
            try
            {
                var department = _mapper.Map<Department>(request);
                var result = await _DepartmentRep.AddAsync(department);
                if (result == 0)
                {
                    Result.Code = (int)CodeEnum.error;
                    Result.Messege = "创建失败";
                }   
            }
            catch (Exception ex)
            {
                    Result.Code = (int)CodeEnum.error;
                    Result.Messege = ex.Message;
            }
            return Result;
        }
    }
}
